<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="mybatis 整体反射框架设计 可以看到，Mybatis对这一块抽象的比较复杂，我们可以看到有几个比较主要的部分：Reflector、Invoker、PropertyTokenizer、MetaClass，MetaObject和ObjectWrapper，下面我们一个一个解析这几个部分，最后合并在一起看看他们是如何协作工作的。 Reflector我对Reflector的理解是 Reflector">
<meta property="og:type" content="article">
<meta property="og:title" content="kyssion-blog">
<meta property="og:url" content="http://yoursite.com/2018/10/09/深入理解mybatis（八）mybatis反射层设计/index.html">
<meta property="og:site_name" content="kyssion-blog">
<meta property="og:description" content="mybatis 整体反射框架设计 可以看到，Mybatis对这一块抽象的比较复杂，我们可以看到有几个比较主要的部分：Reflector、Invoker、PropertyTokenizer、MetaClass，MetaObject和ObjectWrapper，下面我们一个一个解析这几个部分，最后合并在一起看看他们是如何协作工作的。 Reflector我对Reflector的理解是 Reflector">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/10/09/深入理解mybatis（八）mybatis反射层设计/blogimg/mybatis/1.png">
<meta property="og:updated_time" content="2018-10-09T07:22:37.341Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="kyssion-blog">
<meta name="twitter:description" content="mybatis 整体反射框架设计 可以看到，Mybatis对这一块抽象的比较复杂，我们可以看到有几个比较主要的部分：Reflector、Invoker、PropertyTokenizer、MetaClass，MetaObject和ObjectWrapper，下面我们一个一个解析这几个部分，最后合并在一起看看他们是如何协作工作的。 Reflector我对Reflector的理解是 Reflector">
<meta name="twitter:image" content="http://yoursite.com/2018/10/09/深入理解mybatis（八）mybatis反射层设计/blogimg/mybatis/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/09/深入理解mybatis（八）mybatis反射层设计/"/>





  <title> | kyssion-blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">kyssion-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/09/深入理解mybatis（八）mybatis反射层设计/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kyssion">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="kyssion-blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline"></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-09T15:22:37+08:00">
                2018-10-09
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="mybatis-整体反射框架设计"><a href="#mybatis-整体反射框架设计" class="headerlink" title="mybatis 整体反射框架设计"></a>mybatis 整体反射框架设计</h3><p><img src="blogimg/mybatis/1.png" alt=""></p>
<p>可以看到，Mybatis对这一块抽象的比较复杂，我们可以看到有几个比较主要的部分：Reflector、Invoker、PropertyTokenizer、MetaClass，MetaObject和ObjectWrapper，下面我们一个一个解析这几个部分，最后合并在一起看看他们是如何协作工作的。</p>
<h3 id="Reflector"><a href="#Reflector" class="headerlink" title="Reflector"></a>Reflector</h3><p>我对Reflector的理解是 Reflector是对类的描述 ，我们从一段UT开始（代码位于ReflectorTest）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractEntity</span> <span class="keyword">implements</span> <span class="title">Entity</span>&lt;<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Section</span> <span class="keyword">extends</span> <span class="title">AbstractEntity</span> <span class="keyword">implements</span> <span class="title">Entity</span>&lt;<span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testGetSetterType</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ReflectorFactory reflectorFactory = <span class="keyword">new</span> DefaultReflectorFactory();</span><br><span class="line">    Reflector reflector = reflectorFactory.findForClass(Section.class);</span><br><span class="line">    Assert.assertEquals(Long.class, reflector.getSetterType(<span class="string">"id"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个测试方法首先创建了个ReflectorFactory对象，然后用这个factory创建了一个Section类的Reflector，然后判断Section类中id的setter方法是Long类型的。</p>
<p>ReflectorFactory是对Reflector做的一个简单的工厂，提供类反射的缓存（所以反射这块的开销基本上可以不计了，既灵活又快捷）</p>
<p>DefaultReflectorFactory 是 Reflector的默认实现类，用一个ConcurrentMap缓存所有的Reflector示例，它的findForClass方法如下，它首先尝试从map中获取Reflector，获取失败调用Reflector的构造方法创建示例，缓存并返回：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">interface</span> <span class="title">Entity</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function">T <span class="title">getId</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setId</span><span class="params">(T id)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Reflector <span class="title">findForClass</span><span class="params">(Class&lt;?&gt; type)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (classCacheEnabled) &#123;</span><br><span class="line">        <span class="comment">// synchronized (type) removed see issue #461</span></span><br><span class="line">        Reflector cached = reflectorMap.get(type);</span><br><span class="line">        <span class="keyword">if</span> (cached == <span class="keyword">null</span>) &#123;</span><br><span class="line">            cached = <span class="keyword">new</span> Reflector(type);</span><br><span class="line">            reflectorMap.put(type, cached);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> cached;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Reflector(type);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>之后是Reflector的构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">Reflector</span><span class="params">(Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">    type = clazz;</span><br><span class="line">    addDefaultConstructor(clazz);</span><br><span class="line">    addGetMethods(clazz);</span><br><span class="line">    addSetMethods(clazz);</span><br><span class="line">    addFields(clazz);</span><br><span class="line">    readablePropertyNames = getMethods.keySet().toArray(<span class="keyword">new</span> String[getMethods.keySet().size()]);</span><br><span class="line">    writeablePropertyNames = setMethods.keySet().toArray(<span class="keyword">new</span> String[setMethods.keySet().size()]);</span><br><span class="line">    <span class="keyword">for</span> (String propName : readablePropertyNames) &#123;</span><br><span class="line">        caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (String propName : writeablePropertyNames) &#123;</span><br><span class="line">        caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这一块不再细细展开，方法名见名知义，首先将type成员设置为原始的class对象，之后获取class的构造方法，getter/setter属性，成员字段，之后将属性名转大写存放到caseInsensitivePropertyMap中，为了后面的查找，大小写不敏感。</p>
<p>Reflector的其他方法就是对我们保存的这些类的描述做查找， 其中有两个特别的，也就是我们接下来要讨论的 getSetInvoker和 getGetInvoker</p>
<h3 id="Invoker"><a href="#Invoker" class="headerlink" title="Invoker"></a>Invoker</h3><p>Invoker，顾名思义，就是调用，可以调用的东西，他有一个invoke方法，意思就是调用，参数是target和args，就是调用的对象和调用的参数。</p>
<p>我们来看下它的几个实现类：</p>
<ul>
<li>MethodInvoker: 方法调用</li>
<li>SetFieldInvoker：Setter方法调用</li>
<li>GetFieldInvoker：Getter方法调用<br>MethodInvoker中invoke方法的实现：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object target, Object[] args)</span> <span class="keyword">throws</span> IllegalAccessException, InvocationTargetException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> method.invoke(target, args);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>就是简单的method.invoke</p>
<h3 id="PropertyTokenizer"><a href="#PropertyTokenizer" class="headerlink" title="PropertyTokenizer"></a>PropertyTokenizer</h3><p>这个就比较牛逼了，他可以处理属性表达式，PropertyTokenizer还实现了Iterator接口，这意味着他可以处理复杂的嵌套属性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> children != <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> PropertyTokenizer <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> PropertyTokenizer(children);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>字段的含义，name表示当前对象的名字，indexedName是当前对象的名字加上后面的索引（[]）如果有的话，index是索引下标，children是延伸属性（子对象）<br>比如：用PropertyTokenizer去解析 “richType.richList[0].value”，那么 name=richType, indexedName=richType，index=null，children=richList[0].value<br>之后执行tokenizer.next()得到新的tokenizer，此时 name=richList, indexdName=richList[0],index=0, children=value<br>之后我们会结合MetaClass和MetaObject看看他有多牛逼</p>
<h3 id="MetaClass"><a href="#MetaClass" class="headerlink" title="MetaClass"></a>MetaClass</h3><p>MetaClass实际上是对Reflector和ProeprtyTokenizer的一种结合，是我们可以用复杂的属性表达式来获取类型的描述。</p>
<p>同样的，我们结合UT来看看它是怎样工作的，首先是一个示例的复杂类型 RichType</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RichType</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> RichType richType;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String richField;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String richProperty;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Map richMap = <span class="keyword">new</span> HashMap();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> List richList = <span class="keyword">new</span> ArrayList() &#123;</span><br><span class="line">        &#123;</span><br><span class="line">            add(<span class="string">"bar"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RichType <span class="title">getRichType</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> richType;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRichType</span><span class="params">(RichType richType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.richType = richType;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getRichProperty</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> richProperty;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRichProperty</span><span class="params">(String richProperty)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.richProperty = richProperty;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List <span class="title">getRichList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> richList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRichList</span><span class="params">(List richList)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.richList = richList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map <span class="title">getRichMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> richMap;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRichMap</span><span class="params">(Map richMap)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.richMap = richMap;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">shouldCheckGetterExistance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ReflectorFactory reflectorFactory = <span class="keyword">new</span> DefaultReflectorFactory();</span><br><span class="line">    MetaClass meta = MetaClass.forClass(RichType.class, reflectorFactory);</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richField"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richProperty"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richList"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richMap"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richList[0]"</span>));</span><br><span class="line"></span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType.richField"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType.richProperty"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType.richList"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType.richMap"</span>));</span><br><span class="line">    assertTrue(meta.hasGetter(<span class="string">"richType.richList[0]"</span>));</span><br><span class="line"></span><br><span class="line">    assertFalse(meta.hasGetter(<span class="string">"[0]"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这段代码说明了metaClass.hasGetter方法可以接受一个复杂的属性表达式来找到对应的类型描述（利用PropertyTokenizer），这个神奇的功能是这么实现的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasGetter</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    PropertyTokenizer prop = <span class="keyword">new</span> PropertyTokenizer(name);</span><br><span class="line">    <span class="keyword">if</span> (prop.hasNext()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (reflector.hasGetter(prop.getName())) &#123;</span><br><span class="line">            MetaClass metaProp = metaClassForProperty(prop);</span><br><span class="line">            <span class="keyword">return</span> metaProp.hasGetter(prop.getChildren());</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> reflector.hasGetter(prop.getName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>首先检查tokenizer的name字段对应的属性是不是有getter方法，之后迭代子属性，直到最后，children为空。</p>
<p>MetaClass中的还有几个方法的实现和这个类似，hasSetter, getGetterType, getSetterType</p>
<p>以上都是类级别的反射抽象，下面看看对象级别的</p>
<h3 id="ObjectWrapper"><a href="#ObjectWrapper" class="headerlink" title="ObjectWrapper"></a>ObjectWrapper</h3><p>ObjectWrapper是对对象的描述的抽象，它抽象出一系列对对象描述的查询和更新的接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ObjectWrapper</span> </span>&#123;</span><br><span class="line">    <span class="function">Object <span class="title">get</span><span class="params">(PropertyTokenizer prop)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">set</span><span class="params">(PropertyTokenizer prop, Object value)</span></span>;</span><br><span class="line">    <span class="function">String <span class="title">findProperty</span><span class="params">(String name, <span class="keyword">boolean</span> useCamelCaseMapping)</span></span>;</span><br><span class="line">    String[] getGetterNames();</span><br><span class="line">    String[] getSetterNames();</span><br><span class="line">    Class&lt;?&gt; getSetterType(String name);</span><br><span class="line">    Class&lt;?&gt; getGetterType(String name);</span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">hasSetter</span><span class="params">(String name)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">hasGetter</span><span class="params">(String name)</span></span>;</span><br><span class="line">    <span class="function">MetaObject <span class="title">instantiatePropertyValue</span><span class="params">(String name, PropertyTokenizer prop, ObjectFactory objectFactory)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isCollection</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">add</span><span class="params">(Object element)</span></span>;</span><br><span class="line">    &lt;E&gt; <span class="function"><span class="keyword">void</span> <span class="title">addAll</span><span class="params">(List&lt;E&gt; element)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ObjectWrapper有个几个实现类</p>
<ul>
<li>BeanWrapper，包装Javabean的描述，</li>
<li>MapWrapper，包装Map（键值对）的描述</li>
<li>CollectionWrapper，包装Collection（集合）的描述</li>
<li>ObjectWrapperFactory 了操作实例化ObjectWrapper的工厂方法的抽象，可自定义实现</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Object <span class="title">getBeanProperty</span><span class="params">(PropertyTokenizer prop, Object object)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Invoker method = metaClass.getGetInvoker(prop.getName());</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> method.invoke(object, NO_ARGUMENTS);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            <span class="keyword">throw</span> ExceptionUtil.unwrapThrowable(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (RuntimeException e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> e;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ReflectionException(<span class="string">"Could not get property '"</span> + prop.getName() + <span class="string">"' from "</span> + object.getClass() + <span class="string">".  Cause: "</span> + t.toString(), t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">setBeanProperty</span><span class="params">(PropertyTokenizer prop, Object object, Object value)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Invoker method = metaClass.getSetInvoker(prop.getName());</span><br><span class="line">        Object[] params = &#123;value&#125;;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            method.invoke(object, params);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            <span class="keyword">throw</span> ExceptionUtil.unwrapThrowable(t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ReflectionException(<span class="string">"Could not set property '"</span> + prop.getName() + <span class="string">"' of '"</span> + object.getClass() + <span class="string">"' with value '"</span> + value + <span class="string">"' Cause: "</span> + t.toString(), t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="MetaObject"><a href="#MetaObject" class="headerlink" title="MetaObject"></a>MetaObject</h3><p>MetaObject也是对对象的描述，它代理了objectWrapper的大部分方法，和MetaClass一样，它利用PropertyTokenizer做了对复杂属性表达式的处理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">shouldGetAndSetNestedField</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    RichType rich = <span class="keyword">new</span> RichType();</span><br><span class="line">    MetaObject meta = SystemMetaObject.forObject(rich);</span><br><span class="line">    meta.setValue(<span class="string">"richType.richField"</span>, <span class="string">"foo"</span>);</span><br><span class="line">    assertEquals(<span class="string">"foo"</span>, meta.getValue(<span class="string">"richType.richField"</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>MetaObject有5个成员字段，</p>
<ul>
<li>originalObject：原始对象，</li>
<li>objectWrapper，被包装的objectWrapper，</li>
<li>objectFactory，对象创建工厂，用于在setValue方法中创建不存在的对象属性实例，</li>
<li>objectWrapperFactory，创建特定的objectWrapper，</li>
<li>reflectorFactory，用来自定一反射类生成的，如果需要可以自行的扩展</li>
</ul>
<h3 id="协作"><a href="#协作" class="headerlink" title="协作"></a>协作</h3><p>反射层的类互相协作，最终根据入参制作出来一个完美的MetaObject和MetaClass给其他组件使用，这其中，比较重要的方法有：</p>
<p>Configuration.newMetaObject，根据传入的object和配置的factory创建对象描述</p>
<p>实际上，ObjectFactory，ObjectWrapperFactory，ReflectorFactory是可以在XML中配置成自定义的，工厂对象全局单例（Configuration对象中）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">parseConfiguration</span><span class="params">(XNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//issue #117 read properties first</span></span><br><span class="line">        propertiesElement(root.evalNode(<span class="string">"properties"</span>));</span><br><span class="line">        Properties settings = settingsAsProperties(root.evalNode(<span class="string">"settings"</span>));</span><br><span class="line">        loadCustomVfs(settings);</span><br><span class="line">        typeAliasesElement(root.evalNode(<span class="string">"typeAliases"</span>));</span><br><span class="line">        pluginElement(root.evalNode(<span class="string">"plugins"</span>));</span><br><span class="line">        objectFactoryElement(root.evalNode(<span class="string">"objectFactory"</span>));</span><br><span class="line">        objectWrapperFactoryElement(root.evalNode(<span class="string">"objectWrapperFactory"</span>));</span><br><span class="line">        reflectorFactoryElement(root.evalNode(<span class="string">"reflectorFactory"</span>));</span><br><span class="line">        settingsElement(settings);</span><br><span class="line">        <span class="comment">// read it after objectFactory and objectWrapperFactory issue #631</span></span><br><span class="line">        environmentsElement(root.evalNode(<span class="string">"environments"</span>));</span><br><span class="line">        databaseIdProviderElement(root.evalNode(<span class="string">"databaseIdProvider"</span>));</span><br><span class="line">        typeHandlerElement(root.evalNode(<span class="string">"typeHandlers"</span>));</span><br><span class="line">        mapperElement(root.evalNode(<span class="string">"mappers"</span>));</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> BuilderException(<span class="string">"Error parsing SQL Mapper Configuration. Cause: "</span> + e, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>XMlConfigBuilder.settingsAsProperties方法使用MetaClass检查Properties参数有没有非法的key</p>
<p>MetaObject和MetaClass在Session的执行周期（executor, mapping, builder…）中还具有广泛的应用</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/09/英语学习/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/09/深入理解mybatis（四）动态sql/" rel="prev" title="">
                 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">kyssion</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">133</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#mybatis-整体反射框架设计"><span class="nav-number">1.</span> <span class="nav-text">mybatis 整体反射框架设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Reflector"><span class="nav-number">2.</span> <span class="nav-text">Reflector</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Invoker"><span class="nav-number">3.</span> <span class="nav-text">Invoker</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PropertyTokenizer"><span class="nav-number">4.</span> <span class="nav-text">PropertyTokenizer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MetaClass"><span class="nav-number">5.</span> <span class="nav-text">MetaClass</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ObjectWrapper"><span class="nav-number">6.</span> <span class="nav-text">ObjectWrapper</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MetaObject"><span class="nav-number">7.</span> <span class="nav-text">MetaObject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#协作"><span class="nav-number">8.</span> <span class="nav-text">协作</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kyssion</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
